package main

import (
	"fmt"

	"gitee.com/chenhonghua/exercise-repository/entity"
	"gitee.com/chenhonghua/exercise-repository/handler"
	"gitee.com/chenhonghua/ginorigin/database"
	connsqlite "gitee.com/chenhonghua/ginorigin/database/connect/sqlite"
	"gitee.com/chenhonghua/ginorigin/env"
	"gitee.com/chenhonghua/ginorigin/http/restful"
	"gitee.com/chenhonghua/ginorigin/http/router"
	"gitee.com/chenhonghua/ginorigin/log"
)

func main() {
	load_sqlite()
	router.RouterConfig{
		Enable:    true,
		LogEnable: true,
		AllowCors: true,
	}.Load()
	router.SetWriter(log.DefaultLogger.Out)
	v1Group := router.GetRouter().Group("/api/v1")
	v1Group.GET("health", restful.Success)      // 健康检测
	v1Group.GET("query", handler.HANDLER_QUERY) // 查询题目
	if e := router.GetRouter().Run(fmt.Sprintf("0.0.0.0:%d", env.IntVal("SERVER_PORT", 59001))); e != nil {
		log.Fatal(e)
	}
}

func load_sqlite() {
	database.DatabaseConfig{
		Enable:  true,
		LogMode: env.StringVal("SQL_LOG_LEVEL", "error"),
		DBConfig: &connsqlite.Sqlite{
			Path:         env.StringVal("SQLITE_HOST", "exercise_repository.db"),
			MaxIdleConns: env.IntVal("SQLITE_MAX_IDLE_CONN", 5),
			MaxOpenConns: env.IntVal("SQLITE_MAX_OPEN_CONN", 10),
		},
	}.Load()
	log.Info("sqlite database init success")
	
	// migrate
	if e := database.GetConnection().Migrator().AutoMigrate(&entity.Exercise{}, &entity.Option{}); e != nil { // 自动创建、更新表结构
		log.Fatalf("数据库初始化(migrator)-表结构创建和更新-错误：%s", e.Error())
	}
}
